#include<iom16v.h>
#define uchar unsigned char
#define uint unsigned int

uchar Table[10]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f};
uchar Data[4]={0,0,0,1};
uchar Key1,Key2,Key3;

void DelayMs(uchar i)
{
 uchar j;
 for(;i!=0;i++)
 {
  for(j=10;j!=0;j--);
 }
}

void Display(uchar *p)
{
 uchar i,sel=0x01;
 for(i=0;i<4;i++)
 {
  PORTC=sel;
  PORTA=0xff-Table[p[i]];
  DelayMs(2);
  sel=sel<<1;
 }
}

void Key_Process(uchar *p)
{
 while((PINB&0x01)==0){Display(Data);Key1=1;}
 while((PINB&0x02)==0){Display(Data);Key2=1;}
 while((PINB&0x04)==0){Display(Data);Key3=1;}
 if(Key1==1)
 {
  p[3]++;
  if(p[3]==10) p[3]=0;
  Key1=0;
 }
 if(Key2==1)
 {
  p[2]++;
  if(p[2]==10) p[2]=0;
  Key2=0;
 }
 if(Key3==1)
 {
  p[1]++;
  if(p[1]==10) p[1]=0;
  Key3=0;
 }
}

void Set_Process(void)
{
 uint i,j;
 i=Data[0]*1000+Data[1]*100+Data[2]*10+Data[3];
 j=500/i;
 OCR1AH=j>>8;
 OCR1AL=j&0x00ff;
}

void Init_IO(void)
{
 DDRA=0xff;
 PORTA=0xff;
 DDRC=0xff;
 PORTC=0xff;
 DDRB=0x00;
 PORTB=0x00;
 DDRD=0xff;
 PORTD=0xff;
}

void Init_Timer1(void)
{
 TIMSK=TIMSK|0x10;
 TCCR1B=0x0a;
 TCNT1H=0x00;
 TCNT1L=0x00;
 Set_Process();
 SREG=SREG|0x80;
}

void main(void)
{
 Init_IO();
 Init_Timer1();
 DelayMs(50);
 while(1)
 {
  Key_Process(Data);
  Set_Process();
  Display(Data);
 }
}

#pragma interrupt_handler Compare:7
void Compare(void)
{PORTD=~PORTD;}